package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.CategoryService;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /*
     * 菜品分页条件查询
     * */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        // 1. 先开启 PageHelper 分页
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        // 2. 执行数据库查询
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishPageQueryDTO, dish);
        List<Dish> dishes = dishMapper.queryByCondition(dish);

        // 3. 这里 dishes 已经是 PageHelper 处理过的分页数据
        PageInfo<Dish> dishPageInfo = new PageInfo<>(dishes);

        // 4. 进行 VO 转换，但不新建 List，而是遍历 dishPageInfo.getList()
        List<DishVO> dishVOS = dishPageInfo.getList().stream().map(dish1 -> {
            DishVO dishVO = new DishVO();
            Category category = categoryMapper.queryById(dish1.getCategoryId());
            BeanUtils.copyProperties(dish1, dishVO);
            dishVO.setCategoryName(category.getName());
            return dishVO;
        }).collect(Collectors.toList());

        // 5. 返回分页结果
        return new PageResult(dishPageInfo.getTotal(), dishVOS);
    }

    /*
     * 添加菜品及其口味
     * */
    @Override
    @Transactional
    public void add(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (!flavors.isEmpty()) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dish.getId());
            }
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /*
     * 根据id查询菜品及其口味
     * */
    @Override
    public DishVO queryById(Long id) {

        Dish dish = dishMapper.queryById(id);

        List<DishFlavor> dishFlavors = dishFlavorMapper.selectByDishId(id);

        Category category = categoryMapper.getById(dish.getCategoryId());

        return DishVO.builder()
                .id(dish.getId())
                .name(dish.getName())
                .categoryId(dish.getCategoryId())
                .price(dish.getPrice())
                .image(dish.getImage())
                .description(dish.getDescription())
                .status(dish.getStatus())
                .flavors(dishFlavors)
                .categoryName(category.getName())
                .build();
    }

    /*
     * 更新菜品及其口味数据
     * */
    @Override
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //更新菜品数据
        dishMapper.update(dish);
        //更新菜品口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (!flavors.isEmpty()) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dish.getId());
                //现根据dish_id清空dish_flavor，再根据dish_id批量新增
                dishFlavorMapper.deleteByDishId(dish.getId());
            }
            dishFlavorMapper.insertBatch(flavors);
        }

    }

    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        /*
         * 起售菜品不允许删除
         * */
        List<Dish> dishes = dishMapper.getByIds(ids);
        for (Dish dish : dishes) {
            if (dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        /*
         * 被套餐关联的菜品不允许删除
         * */
        List<Setmeal> setmeals = setmealDishMapper.queryByDishIds(ids);
        if (!setmeals.isEmpty()) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        /*
         * 删除菜品和其口味
         * */
        dishMapper.deleteBatch(ids);
        dishFlavorMapper.deleteBatch(ids);
    }

    /*
     * 起售或者停售菜品
     * */
    @Override
    public void enableOrDisable(Long id, Integer status) {
        Dish dish = new Dish();
        dish.setStatus(status);
        dish.setId(id);
        dishMapper.update(dish);
    }

    @Override
    public List<Dish> queryByCategoryId(Long categoryId) {
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        return dishMapper.queryByCondition(dish);
    }

    @Override
    public List<DishVO> queryWithFlavors(Long categoryId) {
        List<Dish> dishes = dishMapper.queryByCategoryId(categoryId);
        List<DishVO> dishVOS = new ArrayList();
        for (Dish dish : dishes) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish,dishVO);
            List<DishFlavor> dishFlavors = dishFlavorMapper.selectByDishId(dish.getId());
            dishVO.setFlavors(dishFlavors);
            dishVOS.add(dishVO);
        }
        return dishVOS;
    }
}
